
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using Swaf;
using Swaf.BizObj;
using Swaf.CodeGen;
using Swaf.Container;
using Swaf.DataAccess;

namespace TestApp
{
	class Program
	{
		static void Main(string[] args)
		{
			string configFile = "SaxWebApplicationUnitTest.xml";
			string homeBaseLoc = System.IO.Directory.GetCurrentDirectory() + @"\..\source\SaxWebSite\";
			IApplication app = Application.create(homeBaseLoc + @"configFiles/" + configFile, homeBaseLoc, homeBaseLoc);

			Console.Read();
			//testDarPerformance(app);
			testInsert(app);
		}

		static void testInsert(IApplication app)
		{
			IBizObj accountEntry = app.bizObjMgr.create("AccountEntry");
			accountEntry.put("id", new Swaf.BGuid.Guid());
			accountEntry.put("date", DateTime.Now);
			accountEntry.put("refNumber", "777");
			accountEntry.put("description", "Test Insert Dar");
			accountEntry.put("account.id", new Swaf.BGuid.Guid("ad197e1c-a4bf-4e31-8126-826cc5a2af0a"));
			accountEntry.put("subAccountEntryId", new Swaf.BGuid.Guid("18810a27-3914-4800-b150-21bb24befab8"));
			accountEntry.put("paymentAmount", "77.77");
			accountEntry.put("postedBy", new Swaf.BGuid.Guid("F624A03C-24D6-4386-A9CD-7EC800ABDB19"));
			app.appData.put("DA.NewInsertAccountEntry", accountEntry);
		}

		static void testDarPerformance(IApplication app)
		{
			FlexiMap m =new FlexiMap();

			List<decimal> timings = new List<decimal>();

			for (int pos = 0; pos < 30; pos++)
			{
				DateTime t1 = DateTime.Now;
				IBizObjList c1 = callDar(app, true);
				//IBizObjList c1 = app.appData.get("DA.NewGetCustomers", m) as IBizObjList;
				DateTime t2 = DateTime.Now;
				IBizObjList c2 = callDar(app, false);
				//IBizObjList c2 = app.appData.get("Data.GetCustomers", m) as IBizObjList;
				DateTime t3 = DateTime.Now;
				string xml1 = c1.Xml;
				string xml2 = c2.Xml;

				//int len1 = xml1.Length;
				//int len2 = xml2.Length;

				long run1 = (t2.Ticks - t1.Ticks)/1000;
				long run2 = (t3.Ticks - t2.Ticks)/1000;
				decimal dif = (decimal)(100 - ((decimal)(run1*100)/run2));
				if (pos > 0)
					timings.Add(dif);
				else
				{
					File.WriteAllText("c1.xml", xml1);
					File.WriteAllText("c2.xml", xml2);
				}
				Console.Out.WriteLine("Time to call: {0}ms - {1}ms. New is {2}ms faster ({3} %)", run1, run2, run2-run1, dif);
			}
			decimal av = 0.0M;
			foreach (decimal d in timings)
				av += d;
			av = av / timings.Count;
			Console.Out.WriteLine("Average dif is {0}%", av);



		}
		static IBizObjList callDar(IApplication app, bool newDar)
		{
			FlexiMap m = new FlexiMap();
			m["accountId"] = new Swaf.BGuid.Guid("ad197e1c-a4bf-4e31-8126-826cc5a2af0a");//"5360e259-5c60-40cf-b104-08476408e384");
			if (!newDar)
				m["criteria"] = "";
			else
			{
				IBizObj criteria = app.bizObjMgr.create("FilterSortOptions");
				m["criteria"] = criteria;
				IBizObjList filters = criteria.get("filterOptions") as IBizObjList;
				IBizObj filter = filters.insertNew();
				//filter.put("field", "AccountEntries.amount");
				//filter.put("criteria", "<");
				//filter.put("value", "-80.00");
				filter.put("field", "AccountEntries.description");
				filter.put("criteria", "c");
				filter.put("value", "whatever");
			}
			//m["accountId"] = new Swaf.BGuid.Guid("5360e259-5c60-40cf-b104-08476408e384");//"5360e259-5c60-40cf-b104-08476408e384");
			object v = app.appData.get(string.Format("{0}.BasicAccounting.{1}GetAccountEntries", newDar?"DA":"Data", newDar?"New":""), m);
			IBizObjList entries = v as IBizObjList;
			if (entries != null)
			{
				return entries;
				//Console.Out.WriteLine(entries.Xml);
				//Console.Out.WriteLine("{0} entries found in list", entries.numElements);
			}
			return null;
		}

		static void doManualCodeGen(IApplication app)
		{
			CodeClass cc = new CodeClass("Swaf.DataAccess.CodeTemplates.DataAccessTemplate", @"d:\dev2007b\trunk\sax\bin");
			cc.addReference("System.dll");
			cc.addReference("System.Data.dll");
			cc.addReference("System.Xml.dll");
			cc.addReference("SwafInterfaces.dll");
			cc.addReference("Swaf.dll");

			cc.CodeBlocks["Formatter"].setFormatedContents("AccountEntryFormatter");
			cc.CodeBlocks["$ClassName"].GeneratedContents = "TestDataAccess";
			cc.CodeBlocks["CreateParamsPre"].setFormatedContents("SqlDbType");
			cc.CodeBlocks["DbCreate"].setFormatedContents("DB.Syrinx");
			cc.CodeBlocks["DbCommandType"].setFormatedContents("SqlCommand", "5");
			cc.CodeBlocks["SqlTrans"].setFormatedContents("SqlTransaction");
			cc.CodeBlocks["CommandTypeStoredProc"].GeneratedContents = "";

			cc.CodeBlocks["CreateParam"].setFormatedContents("SqlDbType", "UniqueIdentifier", "accountId", "0");
			cc.CodeBlocks["CreateParam"].CodeBlocks["SetVal"].setFormatedContents("id");
			cc.CodeBlocks["CreateParam"].CodeBlocks["Dir"].GeneratedContents = "";

			/*
			NamedCodeBlock b = cc.CodeBlocks["CreateParam"].appendFormatedContents("SqlDbType", "VarChar", "name", "0");
			b.CodeBlocks["SetVal"].setFormatedContents("name");
			b.CodeBlocks["Dir"].GeneratedContents = "";

			b = cc.CodeBlocks["CreateParam"].appendFormatedContents("SqlDbType", "VarChar", "city", "0");
			b.CodeBlocks["SetVal"].setFormatedContents("city");
			b.CodeBlocks["Dir"].GeneratedContents = "";

			b = cc.CodeBlocks["CreateParam"].appendFormatedContents("SqlDbType", "DateTime", "dateOfBirth", "0");
			b.CodeBlocks["SetVal"].GeneratedContents = "";
			b.CodeBlocks["Dir"].setFormatedContents("ParameterDirection.Output");
			*/

			cc.CodeBlocks["PutNoResults"].GeneratedContents = "";

			CodeClass accountEntryFormatter = new CodeClass("Swaf.DataAccess.CodeTemplates.BizObjFormatterTemplate");
			accountEntryFormatter.CodeBlocks["Using"].GeneratedContents = "";
			accountEntryFormatter.CodeBlocks["$ClassName"].GeneratedContents = "AccountEntryFormatter";
			accountEntryFormatter.CodeBlocks["UpperName"].setFormatedContents("ACCOUNTENTRY");
			accountEntryFormatter.CodeBlocks["BizObjTypeName"].setFormatedContents("AccountEntry");
			accountEntryFormatter.CodeBlocks["ReaderColNames"].GeneratedContents = "";
			accountEntryFormatter.CodeBlocks["RequiresParentName"].GeneratedContents = "false";
			accountEntryFormatter.CodeBlocks["CustomDek"].GeneratedContents = "IBizObj LastBizObj = null;";
			accountEntryFormatter.CodeBlocks["CustomBizObjProcessing"].CodeBlocks["Code"].GeneratedContents = @"
Decimal d = (LastBizObj == null)?(decimal)0.0:(Decimal)LastBizObj.get(""runningBalance"");
d +=(Decimal)CurrentBizObj.get(""total"");
CurrentBizObj.put(""runningBalance"", d);
LastBizObj = CurrentBizObj;
";

			/* For getting singe bizobj
			accountEntryFormatter.CodeBlocks["formatBizObjList"].GeneratedContents = "";
			accountEntryFormatter.CodeBlocks["formatBizObjListMerge"].GeneratedContents = "";
			accountEntryFormatter.CodeBlocks["FormatReturnList"].GeneratedContents = "";
			accountEntryFormatter.CodeBlocks["getBizObjMerge"].GeneratedContents = "";
			accountEntryFormatter.CodeBlocks["getBizObjList"].GeneratedContents = "";
			accountEntryFormatter.CodeBlocks["BizObjListDek"].GeneratedContents = "";
			*/
			//For bizobjlist
			accountEntryFormatter.CodeBlocks["formatBizObj"].GeneratedContents = "";
			accountEntryFormatter.CodeBlocks["formatBizObjList"].setFormatedContents("AccountEntry");
			accountEntryFormatter.CodeBlocks["formatBizObjListMerge"].GeneratedContents = "";
			accountEntryFormatter.CodeBlocks["FormatReturnObj"].GeneratedContents = "";
			accountEntryFormatter.CodeBlocks["getBizObjObj"].GeneratedContents = "";
			accountEntryFormatter.CodeBlocks["getBizObjList"].CodeBlocks["setupList"].GeneratedContents = ""; 
			accountEntryFormatter.CodeBlocks["getBizObjMerge"].GeneratedContents = "";

			accountEntryFormatter.CodeBlocks["SingleFieldKey"].setFormatedContents("ID");
			accountEntryFormatter.CodeBlocks["MultiFieldKeyPre"].GeneratedContents = "";
			accountEntryFormatter.CodeBlocks["MultiFieldKey"].GeneratedContents = "";
			accountEntryFormatter.CodeBlocks["MultiFieldKeyPost"].GeneratedContents = "";
			accountEntryFormatter.CodeBlocks["CreateHomoType"].setFormatedContents("AccountEntry");
			accountEntryFormatter.CodeBlocks["CreateTypeFromField"].GeneratedContents = "";

			accountEntryFormatter.CodeBlocks["ParentNode"].GeneratedContents = "";
			accountEntryFormatter.CodeBlocks["ConstructorParam"].GeneratedContents = "";
			accountEntryFormatter.CodeBlocks["SetupParam"].GeneratedContents = "";
			accountEntryFormatter.CodeBlocks["getBizObjObj"].CodeBlocks["HasParent"].GeneratedContents = "";			

			accountEntryFormatter.CodeBlocks["AddChildNode"].setFormatedContents("account", "accountFormatter(this)");
			accountEntryFormatter.CodeBlocks["AddChildNode"].appendFormatedContents("subEntries", "subEntriesFormatter(this)");


			CodeClass accountFormatter = new CodeClass("Swaf.DataAccess.CodeTemplates.BizObjFormatterTemplate");
			accountFormatter.CodeBlocks["Using"].GeneratedContents = "";
			accountFormatter.CodeBlocks["$ClassName"].GeneratedContents = "accountFormatter";
			accountFormatter.CodeBlocks["UpperName"].setFormatedContents("ACCOUNT");
			accountFormatter.CodeBlocks["BizObjTypeName"].setFormatedContents("Account");
			accountFormatter.CodeBlocks["ReaderColNames"].GeneratedContents = "";
			accountFormatter.CodeBlocks["ChildNodeInfoTypes"].GeneratedContents = "";
			accountFormatter.CodeBlocks["ChildNodes"].GeneratedContents = "";
			accountFormatter.CodeBlocks["AddChildNode"].GeneratedContents = "";
			accountFormatter.CodeBlocks["RequiresParentName"].GeneratedContents = "true";
			accountFormatter.CodeBlocks["CustomBizObjProcessing"].GeneratedContents = "";

			accountFormatter.CodeBlocks["formatBizObjList"].GeneratedContents = "";
			accountFormatter.CodeBlocks["formatBizObjListMerge"].GeneratedContents = "";
			accountFormatter.CodeBlocks["FormatReturnList"].GeneratedContents = "";
			accountFormatter.CodeBlocks["getBizObjMerge"].GeneratedContents = "";
			accountFormatter.CodeBlocks["getBizObjList"].GeneratedContents = "";
			accountFormatter.CodeBlocks["BizObjListDek"].GeneratedContents = "";

			accountFormatter.CodeBlocks["SingleFieldKey"].setFormatedContents("ID");
			accountFormatter.CodeBlocks["MultiFieldKeyPre"].GeneratedContents = "";
			accountFormatter.CodeBlocks["MultiFieldKey"].GeneratedContents = "";
			accountFormatter.CodeBlocks["MultiFieldKeyPost"].GeneratedContents = "";
			accountFormatter.CodeBlocks["CreateHomoType"].setFormatedContents("Account");
			accountFormatter.CodeBlocks["CreateTypeFromField"].GeneratedContents = "";

			accountFormatter.CodeBlocks["ParentNode"].CodeBlocks["Type"].GeneratedContents = "AccountEntryFormatter";
			accountFormatter.CodeBlocks["ConstructorParam"].CodeBlocks["Type"].GeneratedContents = "AccountEntryFormatter";
			accountFormatter.CodeBlocks["getBizObjObj"].CodeBlocks["HasParent"].setFormatedContents("account");

			accountEntryFormatter.CodeBlocks["ChildNodeInfoTypes"].setFormatedContents(accountFormatter.generateClassText());

			CodeClass subEntriesFormatter = new CodeClass("Swaf.DataAccess.CodeTemplates.BizObjFormatterTemplate");
			subEntriesFormatter.CodeBlocks["Using"].GeneratedContents = "";
			subEntriesFormatter.CodeBlocks["$ClassName"].GeneratedContents = "subEntriesFormatter";
			subEntriesFormatter.CodeBlocks["UpperName"].setFormatedContents("SUBENTRIES");
			subEntriesFormatter.CodeBlocks["BizObjTypeName"].setFormatedContents("AccountSubEntry");
			subEntriesFormatter.CodeBlocks["ReaderColNames"].GeneratedContents = "";
			subEntriesFormatter.CodeBlocks["ChildNodeInfoTypes"].GeneratedContents = "";
			subEntriesFormatter.CodeBlocks["ChildNodes"].GeneratedContents = "";
			subEntriesFormatter.CodeBlocks["AddChildNode"].GeneratedContents = "";
			subEntriesFormatter.CodeBlocks["RequiresParentName"].GeneratedContents = "true";
			subEntriesFormatter.CodeBlocks["CustomBizObjProcessing"].GeneratedContents = "";

			subEntriesFormatter.CodeBlocks["formatBizObj"].GeneratedContents = "";
			subEntriesFormatter.CodeBlocks["formatBizObjList"].GeneratedContents = "";
			subEntriesFormatter.CodeBlocks["formatBizObjListMerge"].GeneratedContents = "";
			subEntriesFormatter.CodeBlocks["FormatReturnObj"].GeneratedContents = "";
			subEntriesFormatter.CodeBlocks["getBizObjList"].CodeBlocks["setupList"].setFormatedContents("subEntries");
			subEntriesFormatter.CodeBlocks["getBizObjObj"].GeneratedContents = "";
			subEntriesFormatter.CodeBlocks["getBizObjMerge"].GeneratedContents = "";

			subEntriesFormatter.CodeBlocks["SingleFieldKey"].setFormatedContents("ID");
			subEntriesFormatter.CodeBlocks["MultiFieldKeyPre"].GeneratedContents = "";
			subEntriesFormatter.CodeBlocks["MultiFieldKey"].GeneratedContents = "";
			subEntriesFormatter.CodeBlocks["MultiFieldKeyPost"].GeneratedContents = "";
			subEntriesFormatter.CodeBlocks["CreateHomoType"].setFormatedContents("AccountSubEntry");
			subEntriesFormatter.CodeBlocks["CreateTypeFromField"].GeneratedContents = "";

			subEntriesFormatter.CodeBlocks["ParentNode"].CodeBlocks["Type"].GeneratedContents = "AccountEntryFormatter";
			subEntriesFormatter.CodeBlocks["ConstructorParam"].CodeBlocks["Type"].GeneratedContents = "AccountEntryFormatter";

			accountEntryFormatter.CodeBlocks["ChildNodeInfoTypes"].appendFormatedContents(subEntriesFormatter.generateClassText());

			StringBuilder buff = new StringBuilder();

			buff.Append("sql.Append(@\"").Append(@"SELECT
		AccountEntries.id, AccountEntries.accountId, 
		AccountEntries.refNumber,
		AccountEntries.date, AccountEntries.description, AccountEntries.postedBy,
		AccountEntries.status, AccountEntries.amount, AccountSubEntries.id AS subEntriesid, AccountSubEntries.accountEntryId AS subEntriesparentId,
		AccountSubEntries.accountId as subEntriesaccountId, AccountSubEntries.amount AS subEntriesamount, AccountSubEntries.description AS subEntriesdescription
		FROM
		AccountEntries
		INNER JOIN
		AccountSubEntries ON AccountEntries.id = AccountSubEntries.accountEntryId
		INNER JOIN
		Accounts ON Accounts.Id = AccountSubEntries.accountId
		WHERE").Append("\");\n");
			buff.Append(@"if(criteria != null) {
			IBizObjList filters = criteria.get(""filterOptions"") as IBizObjList;
			int count = filters.numElements;
			for(int p = 0; p < count; p++)
			{
				IBizObj f = filters[p];
				if(base.fieldValNeedsQuote(f.get(""field"")))
					sql.AppendFormat("" {0} {1} '{2}'"", f.get(""field""), f.get(""criteria""), f.get(""value""));
				else
					sql.AppendFormat("" {0} {1} {2}"", f.get(""field""), f.get(""criteria""), f.get(""value""));
				if(p < count-1)
					sql.Append(criteria.get(""filterIsAnd"").Equals(true)?"" AND"":"" OR"");
			}
			}
");
			buff.Append("sql.Append(@\"").Append(@"		AccountEntries.accountId = @accountId
		ORDER BY
		AccountEntries.date, AccountEntries.refNumber
").Append("\");\n");
			cc.CodeBlocks["CreateSqlMainBody"].GeneratedContents = buff.ToString();

			cc.CodeBlocks["FormatterClass"].GeneratedContents = accountEntryFormatter.generateClassText();

			//string generatedClass = cc.generateClassText();
			//Console.WriteLine(generatedClass);


			string dataAccessClassName = cc.CodeBlocks["Namespace"].GeneratedContents + "." + cc.CodeBlocks["$ClassName"].GeneratedContents;
			object obj = cc.createInstance(dataAccessClassName);
			Swaf.DataAccess.AdoNet.AdoNetDataAccess dar = obj as Swaf.DataAccess.AdoNet.AdoNetDataAccess;
			FlexiMap m = new FlexiMap();
			m["id"] = new Swaf.BGuid.Guid("5360e259-5c60-40cf-b104-08476408e384");
			object retval = dar.execute(m);
			if (retval is IBizObj)
				Console.WriteLine(((IBizObj)retval).Xml);
			else if (retval is IBizObjList)
			{
				Console.WriteLine(((IBizObjList)retval).Xml);
			}
			else if (retval != null)
				Console.WriteLine("{0}", retval);
		}
	}
}
